package com.ccb.jyzx.expand.tiantouonline.job;

import com.ccb.jyzx.expand.tiantouonline.utils.ConstantUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ScheduledFuture;

/**
 * 动态 定时任务 启动关闭 器
 * @projectName: extend
 * @author: jianghaolin
 * @date: 2019/11/21
 * @version: 1.0
 */
@Component
public class DynamicScheduledTask {

    public final  int  methodNumber = 10;

    @Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;
    @Autowired
    BathchJobRunnable bathchJobRunnable;

    @Bean
    public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
        ThreadPoolTaskScheduler threadPoolTaskScheduler =  new ThreadPoolTaskScheduler();
        threadPoolTaskScheduler.setPoolSize(11);
        return threadPoolTaskScheduler ;
    }

    private List<ScheduledFuture<?>> listFuture = new ArrayList<ScheduledFuture<?>>();

    private String cron = "1 * * * * ?";
    public String getCron() {
        return cron;
    }

    public void setCron(String cron,String id) {
        this.cron = cron;
        stopCron(id);
        Trigger trigger = new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                if ("".equals(cron) || cron == null)
                {
                    return null;
                }
                // 定时任务触发，可修改定时任务的执行周期
                CronTrigger trigger = new CronTrigger(cron);
                Date nextExecDate = trigger.nextExecutionTime(triggerContext);
                return nextExecDate;
            }
        };
        if(id.equals(ConstantUtil.EXE_TAG_ID_AM) || id.equals(ConstantUtil.EXE_TAG_ID_PM) ){
            for(int i = 0; i<methodNumber;i++){
                BathchJobRunnable runnable = new BathchJobRunnable();
                runnable.setMethodIndex(i);
                runnable.setBatchJobExecute(bathchJobRunnable.getBatchJobExecute());
                listFuture.add((ScheduledFuture<?>) threadPoolTaskScheduler.schedule(runnable,trigger ));
            }
        }


    }

    public void stopCron(String id) {
        if(id.equals(ConstantUtil.EXE_TAG_ID_AM)){
            if (listFuture != null&&listFuture.size()!=0) {
                for(ScheduledFuture future:listFuture){
                    //取消任务调度
                    future.cancel(true);
                }
            }
        }
    }

}
